package com.linc.skill.thread;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.android.widget.demo.R;

public class RunnableActivity extends AppCompatActivity {
    private static final String TAG = "RunnableActivity";
    private Thread mThread;
    private boolean mThreadFlag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_runnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy");
    }

    public void onTestClick(View view) {
        mThread = new Thread(new NumberCountThread());
        mThread.start();
    }

    public void onStopClick(View view) {
        mThreadFlag = false;
//        mThread.interrupt();
        if(mThread.isAlive()) {
            Log.d(TAG,"alive");
        } else {
            Log.d(TAG,"dead");
        }
    }

    private class NumberCountThread implements Runnable {
        public void run() {
            int i = 0;
//            while (!Thread.currentThread().isInterrupted()) {
//            while (true) {
            while (mThreadFlag) {
                Log.d(TAG, "count: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
        }
    }
}
